package g

import (
	"encoding/json"
	"sync"

	"github.com/toolkits/file"
)

type GlobalConfig struct {
	Debug      bool             `json:"debug"`
	IP         string           `json:"ip"`
	Host       string           `json:"host"`
	Province   string           `json:"province"`
	City       string           `json:"city"`
	Operator   string           `json:"operator"`
	RPCServer  *RPCServerConfig `json:"rpcserver"`
	HTTPServer string           `json:"httpserver"`
	Heartbeat  *HeartbeatConfig `json:"heartbeat"`
	RPC        *RPCConfig       `json:"rpc"`
}

type RPCServerConfig struct {
	Enabled bool   `json:"enabled"`
	Addr    string `json:"addr"`
	Timeout int    `json:"timeout"`
}

type HeartbeatConfig struct {
	Enabled  bool `json:"enabled"`
	Interval int  `json:"interval"`
}

type RPCConfig struct {
	Enabled bool   `json:"enabled"`
	Listen  string `json:"listen"`
}

var (
	ConfigFile string
	config     *GlobalConfig
	lock       = new(sync.RWMutex)
)

func Config() *GlobalConfig {
	lock.RLock()
	defer lock.RUnlock()
	return config
}

//需判断是否本地，线上agent获取外网IP
func IP() string {
	ip := Config().IP
	if ip != "" {
		// use ip in configuration
		return ip
	}

	if Config().Host == "local" {
		if len(LocalIps) > 0 {
			ip = LocalIps[0]
		}
	} else {
		ip = NetworkIp
	}

	return ip
}

func ParseConfig(cfg string) {
	if cfg == "" {
		Logger.Error("use -c to specify configuration file")
	}

	if !file.IsExist(cfg) {
		Logger.Error("config file:", cfg, "is not existent. maybe you need `mv cfg.example.json cfg.json`")
	}

	ConfigFile = cfg

	configContent, err := file.ToTrimString(cfg)
	if err != nil {
		Logger.Error("read config file:", cfg, "fail:", err)
	}

	var c GlobalConfig
	err = json.Unmarshal([]byte(configContent), &c)
	if err != nil {
		Logger.Error("parse config file:", cfg, "fail:", err)
	}

	lock.Lock()
	defer lock.Unlock()

	config = &c

	Logger.Info("read config file successfully")
}
